<?php

namespace App\GatewayWorker;

use App\Jobs\User\UserUpdateSystemInfoJob;
use App\Jobs\UserOnlineBroadcastJob;
use App\Wen\Utils\GatewayUtils;
use App\Wen\Utils\UserUtils;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class Events
{
    public static function onWorkerStart($businessWorker)
    {
        echo "minisns BusinessWorker Start, welcome\n";
    }

    public static function onConnect($client_id)
    {
        GatewayUtils::success($client_id, 1);
        UserOnlineBroadcastJob::dispatch(0, $client_id)->delay(Carbon::now()->addSeconds(30));
        UserUpdateSystemInfoJob::dispatch(0, $client_id)->delay(Carbon::now()->addSeconds(5));
    }

    public static function onWebSocketConnect($client_id, $data)
    {

    }

    public static function onMessage($client_id, $message)
    {
        $message_arr = GatewayUtils::pre_client_message($message);

        if(_empty_($message_arr)){
            return GatewayUtils::fail($client_id, 200001);
        }
        $mode = $message_arr['mode'];
        $uid = $message_arr['uid'] ?? 0;
        $device = _array_key($message_arr, 'device', '');
        if($device){
            if(!in_array($device, ['app', 'h5', 'mp', 'pc'])){
                $device = '';
            }
        }

        if($mode == 'bind'){
            if(_empty_($uid)){
                return GatewayUtils::fail($client_id, 200015);
            }
            try {
                Cache::forget('websocket:uid2clientid:'.$uid);
                Cache::forget('websocket:clientid2uid:'.$client_id);

                Cache::put('websocket:uid2clientid:'.$uid, $client_id, 300);
                Cache::put('websocket:clientid2uid:'.$client_id, $uid, 300);
                UserUtils::add_user_experience($uid, 0);
                UserUtils::set_online($uid, $device);
                return GatewayUtils::success($client_id, 0);
            }catch (\Exception $e){
                _logger_(__file__, __line__, $e->getMessage());
            }
        }else if($mode == 'ping'){

        }

    }

    public static function onClose($client_id)
    {
//        $uid = Cache::get('websocket:clientid2uid:'.$client_id);
//        if($uid){
//            Cache::forget('websocket:uid2clientid:'.$uid);
//            Cache::forget('websocket:clientid2uid:'.$client_id);
//        }
//        GatewayUtils::success($client_id, 3);
    }
}
